﻿using System;
using System.Collections;

namespace ConsoleDemo
{
    internal class IEnumeratorDemo
    {
        public static void IEnumeratorTest()
        {
            int[] arr1 = { 10, 11, 12, 13, 14 };

            IEnumerator ie = arr1.GetEnumerator();
            while (ie.MoveNext())
            {
                int item = (int)ie.Current;
                Console.WriteLine(item);
            }

            string[] arr2 = { "praise", "What have you withdrawn", "despite what people say", "there is no real hammer", "vocabulary" };
            IEnumerator ie2 = arr2.GetEnumerator();
            while (ie2.MoveNext())
            {
                Console.WriteLine(ie2.Current);
            }
        }

        /// <summary>
        /// 一个可枚举类的完整示例
        /// 3. 调用
        /// </summary>
        public static void CallExample()
        {
            Spectrum spectrum = new Spectrum();
            foreach (string color in spectrum)
            {
                Console.WriteLine(color);
            }
        }
    }

    /// <summary>
    /// 一个可枚举类的完整示例
    /// 2. 实现 IEnumerable 接口
    /// </summary>
    internal class Spectrum : IEnumerable
    {
        string[] colors = { "Red", "Yellow", "Blue" };
        public IEnumerator GetEnumerator()
        {
            return new ColorEnumerator(colors);
        }
    }

    /// <summary>
    /// 一个可枚举类的完整示例
    /// 1. 实现 IEnumerator
    /// </summary>
    internal class ColorEnumerator : IEnumerator
    {
        string[] colors;
        int position = -1;

        public ColorEnumerator(string[] colors)
        {
            this.colors = colors;
        }
        public object Current
        {
            get
            {
                if (position == -1 || position >= colors.Length)
                {
                    return new InvalidOperationException();
                }
                return colors[position];
            }
        }

        public bool MoveNext()
        {
            if (position < colors.Length - 1)
            {
                position++;
                return true;
            }
            return false;
        }

        public void Reset()
        {
            position = -1;
        }
    }
}
